<?php
namespace PsiFramework\Applications\DefaultApp\Classes\DAO;

use PsiFramework\Classes\Util\Database\Query\SqlOrder;

use PsiFramework\Classes\Util\Database\Filters\Paginator;

use PsiFramework\Classes\Util\Database\Filters\QueryFilter;

use PsiFramework\Classes\Util\Database\Query\SqlOperation;

use PsiFramework\Classes\Util\Database\Query\SqlValue;

use PsiFramework\Classes\Util\Database\Query\SqlColumn;

use \PsiFramework\Classes\DAO\AbstractDAO;
use \PsiFramework\Classes\Model\Object;
use \PsiFramework\Classes\Util\Parameters\ObjectParameters;
use \PsiFramework\Applications\DefaultApp\Classes\Model\Message;

/**
 * PsiFramework
 * Php Simple Framework
 *
 * @author Rémi San
 * @version beta
 */

/**
 * The MessageDAO class is the Data Access Object for class Message
 *
 * @package DAO
 */
class MessageDAO extends AbstractDAO
{

    protected static $_singleton = null;

    /**
     * 
     * @param User $user
     * 
     * @return array
     */
    public function retrieveConversations(/*User*/ $user)
    {
        
        $colSender = new SqlColumn('sender');
        $colRecipient = new SqlColumn('recipient');
        
        $sqlValue = new SqlValue($user->getId());
        
        $op = new SqlOperation(SqlOperation::$equal);
        $op->addParameter($colSender);
        $op->addParameter($sqlValue);
        
        $op2 = new SqlOperation(SqlOperation::$equal);
        $op2->addParameter($colRecipient);
        $op2->addParameter($sqlValue);
        
        $or = new SqlOperation(SqlOperation::$or);
        $or->addParameter($op);
        $or->addParameter($op2);
        
        $paginator = new Paginator();
        $paginator->addOrder(new SqlOrder(new SqlColumn('conversation_id'), SqlOrder::$desc));
        
        $result = $this->retrieveAll(new QueryFilter($or), $paginator);
        
        return $this->organiseMessages($result);
    }
    
    public function organiseMessages(/*Message*/ $messages)
    {
        
        $orderedMessages = array();
        
        foreach ($messages as $message) {
            if (!array_key_exists($message->getConversationId(), $orderedMessages)) {
                $orderedMessages[$message->getConversationId()] = array();
            }
            $orderedMessages[$message->getConversationId()][] = $message;
        }
        
        return $orderedMessages;
    }
    
    /**
     * Function to be called instead of the constructor.
     *
     * @return MessageDAO instance
     */
    public static function getInstance(ObjectParameters $objectParameters)
    {
        if (self::$_singleton==null) {
            self::$_singleton = new MessageDAO($objectParameters);
        }
        return self::$_singleton;
    }
}